<script lang="ts" setup>
import type { ConfigModel } from '#/api/system/models';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { createConfigApi, updateConfigApi } from '#/api/system/config';
import { $t } from '#/locales';

import { useSchema } from '../data';

const emit = defineEmits<{
  success: [];
}>();

const formData = ref<ConfigModel>();

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  schema: useSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (valid) {
      modalApi.lock();
      const data = await formApi.getValues();
      try {
        await (formData.value?.id
          ? updateConfigApi(formData.value.id, data)
          : createConfigApi(data));
        modalApi.close();
        emit('success');
      } finally {
        modalApi.unlock();
      }
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<ConfigModel>();
      formData.value = data;
      formApi.setValues(data, false);
      modalApi.setState({
        title: data?.id
          ? $t('ui.actionTitle.edit', ['配置'])
          : $t('ui.actionTitle.create', ['配置']),
      });
    }
  },
});
</script>

<template>
  <Modal>
    <Form />
  </Modal>
</template>
